//
//  ViewController.m
//  ImageSlicer
//
//  Created by 周国勇 on 11/5/14.
//  Copyright (c) 2014 周国勇. All rights reserved.
//

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

#pragma mark - Action

- (IBAction)createButtonClicked:(id)sender {
//    NSLog(@"%@", self.pathTextField.stringValue);
    CGFloat scale = 2/3.0;

    NSURL *pathURL = [NSURL URLWithString:self.pathTextField.stringValue];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray * dirContents =
    [fm contentsOfDirectoryAtURL:pathURL
      includingPropertiesForKeys:@[]
                         options:NSDirectoryEnumerationSkipsHiddenFiles
                           error:nil];
    NSPredicate * fltr = [NSPredicate predicateWithFormat:@"pathExtension='png'"];
    NSArray * onlyPNGs = [dirContents filteredArrayUsingPredicate:fltr];
    
    for (NSURL *url in onlyPNGs) {
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSImage *image = [[NSImage alloc] initWithData:data];
        NSLog(@"old size.w:%f h:%f", image.size.width, image.size.height);

        NSImage *resizedImage = [self imageResize:image newSize:NSMakeSize(image.size.width*scale/2, image.size.height*scale/2)];
        NSLog(@"new size.w:%f h:%f", resizedImage.size.width, resizedImage.size.height);
        
        // 判断是否包含3x后缀
        if ([url.path.lastPathComponent rangeOfString:@"@3x"].location != url.path.lastPathComponent.length-4-3) {
            // 重新保存原来的image
            NSMutableString *renamedName = [NSMutableString stringWithString:url.path.lastPathComponent];
            [renamedName insertString:@"@3x" atIndex:renamedName.length-4];
            NSURL *renamedURL = [pathURL URLByAppendingPathComponent:renamedName];
            NSError *error = nil;
            [fm moveItemAtPath:url.path toPath:renamedURL.path error:&error];
            if (error) {
                NSLog(@"error :%@", error.localizedDescription);
            }
            
            // 保存scale后的image
            NSMutableString *resizedName = [NSMutableString stringWithString:url.path.lastPathComponent];
            [resizedName insertString:@"@2x" atIndex:resizedName.length-4];
            data = [resizedImage TIFFRepresentation];
            NSURL *resizedURL = [pathURL URLByAppendingPathComponent:resizedName];
            [data writeToFile:resizedURL.path atomically:YES];
        }else{
            // 保存scale后的image
            NSMutableString *resizedName = [NSMutableString stringWithString:url.path.lastPathComponent];
            [resizedName deleteCharactersInRange:NSMakeRange(url.path.lastPathComponent.length-4-3, 3)];

            [resizedName insertString:@"@2x" atIndex:resizedName.length-4];
            NSData *data1 = [resizedImage TIFFRepresentation];
            NSURL *resizedURL = [pathURL URLByAppendingPathComponent:resizedName];
            [data1 writeToFile:resizedURL.path atomically:YES];
        }


    }
}

- (NSImage *)imageResize:(NSImage*)anImage newSize:(NSSize)newSize {
    NSImage *sourceImage = anImage;
//    [sourceImage setScalesWhenResized:YES];
    
    // Report an error if the source isn't a valid image
    if (![sourceImage isValid]){
        NSLog(@"Invalid Image");
    } else {
        NSImage *smallImage = [[NSImage alloc] initWithSize: newSize];
        [smallImage lockFocus];
        [sourceImage setSize: newSize];
        [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
        [sourceImage drawAtPoint:NSZeroPoint fromRect:CGRectMake(0, 0, newSize.width, newSize.height) operation:NSCompositeCopy fraction:1.0];
        [smallImage unlockFocus];
        return smallImage;
    }
    return nil;
}
@end
